package svc

import (
	aredis "github.com/go-redis/redis/v7"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/rest"
	"{{cookiecutter.app_name}}/internal/config"
	"{{cookiecutter.app_name}}/internal/middleware"
	{% if cookiecutter.use_mysql == 'y' -%}
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	{%- endif %}
)

type ServiceContext struct {
	Config   config.Config
	JwtExt   rest.Middleware
	JwtAdmin rest.Middleware

	{% if cookiecutter.use_mysql == 'y' -%}
	SqlConn    sqlx.SqlConn
	{%- endif %}
	{% if cookiecutter.use_redis == 'y' %}
	CacheRedis cache.CacheConf
	Redis      *redis.Redis
	ARedis     *aredis.Client
	{% endif %}
}

func NewServiceContext(c config.Config) *ServiceContext {
	logx.Info("{{cookiecutter.app_name}} start ")
	{% if cookiecutter.use_mysql == 'y' %}
	// 使用mysql的model的话使用下面的mysql连接初始化model
	//conn := sqlx.NewMysql(c.Mysql.DataSource)
	{% endif %}
	{% if cookiecutter.use_redis == 'y' %}
	newRedis := redis.New(c.Redis.Address, redisConfig(c))
	{% endif %}
	//rds := redis.NewRedis("localhost:6379", redis.NodeType)
	//rawConn, err := rds.RawConn()
	//if err != nil {
	//	panic(err) // handle error accordingly
	//}

	{% if cookiecutter.use_redis == 'y' %}
	client := aredis.NewClient(&aredis.Options{
		Addr:     c.Redis.Address,
		Password: c.Redis.Pass,
		DB:       0,
	})
	{% endif %}
	

	return &ServiceContext{
		Config:   c,
		{% if cookiecutter.use_redis == 'y' %}
		ARedis:   client,
		{% endif %}
		{% if cookiecutter.use_redis == 'y' %}
		JwtExt:   middleware.NewJwtExtMiddleware(newRedis, c.APP).Handle,
		JwtAdmin: middleware.NewJwtAdminMiddleware(newRedis, c.APP).Handle,
		//SqlConn:           conn,
		Redis:               newRedis,
		{% endif %}
	}
}

func redisConfig(c config.Config) redis.Option {
	return func(r *redis.Redis) {
		r.Type = redis.NodeType
		r.Pass = c.Redis.Pass
	}
}
